﻿using LogLib;
using Microsoft.Extensions.Configuration;
using Nini.Config;
using System;
using System.Reflection;

namespace USBControlLib.Settings
{
    public class ConfigService
    {
        #region static fields
        private const string ConfigFileName = "USBControlConfig.ini";

        private static ConfigService Instance;

        public static ConfigService Get()
        {
            if (Instance != null)
            {
                return Instance;
            }
            Instance = new ConfigurationBuilder()
                .AddIniFile($".\\{ConfigFileName}")
                .Build()
                .Get<ConfigService>();
            return Instance;
        }

        public static void SaveConfig<T>(T value, string section) where T : class, new()
        {
            Type type = value.GetType();
            IniConfigSource source = new IniConfigSource(ConfigFileName);
            IConfig config = source.Configs[section];
            PropertyInfo[] pArray = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            foreach (PropertyInfo pi in pArray) 
            {
                string field = pi.Name;
                object val = pi.GetValue(value, null);
                if (val == null)
                {
                    continue;
                }
                object valOld = config.Get(field);
                if(!val.ToString().Equals(valOld.ToString()))
                {
                    config.Set(field, val);
                }
            }
            source.Save();
        }
        #endregion

        public USBConnectSetting BoardConfig { get; set; } = new USBConnectSetting();

        public USBControlSetting Batch { get; set; } = new USBControlSetting();
    }
}
